<?php

namespace app\admin\controller;

/**
 * @title 商品相关
 */
class Goods extends Common
{


    /**
     * @title 查询商品列表
     * @desc  {"0":"接口地址：http://api.huaxiaoujia.com/index/goods/query","1":"请求方式：GET","2":"接口备注：必传参数用于加密验证"}
     * @param {"name":"goods_id","type":"int","required":true,"default":"","desc":"商品ID"}
     * @return {"name":"goodsId","type":"int","required":true,"desc":"商品ID","level":1}
     * @return {"name":"goodsName","type":"string","required":true,"desc":"商品名称","level":1}
     * @return {"name":"originalImg","type":"string","required":true,"desc":"商品封面图片","level":1}
     * @return {"name":"salesSum","type":"int","required":true,"desc":"商品销量","level":1}
     * @return {"name":"priceList","type":"array","required":true,"desc":"商品规格集合","level":1}
     * @return {"name":"content","type":"array","required":true,"desc":"商品介绍图片集合","level":1}
     * @return {"name":"collection","type":"boolean","required":true,"desc":"是否收藏","level":1}
     */

    public function query()
    {
        $this->isCheckAuth();
        $admin = $this->getUserInfo();
        $page = input('page') > 0 ? input('page') : 1;
        $listRows = input('listRows') > 0 ? input('listRows') : 20;
        $db = model('Goods');
        //判断通过商品编码搜索商品其他条件将不生效
        if (input('goods_sn')) {
            $db->where('goods_sn', input('goods_sn'));
        } else {
            if (input('key')) {
                $db->where('goods_name', 'like', "%" . input('key') . "%");
            }
            if (input('status') != '') {
                $db->where('is_on_sale', input('status'));
            } else {
                $db->where('is_on_sale', "1");
            }
            if (input("category") > 0) {
                $category = input("category");
                $db->join("k_goods_category gc", "k_goods.cat_id = gc.id")->where("gc.id = $category");
            }
        }
        if (input("order")) {
            switch (input("order")) {
                case "sort_default":
                    $db->order("goods_id", "desc");
                    break;
                case "sort_price":
                    $db->join("k_spec_goods_price r", "k_goods.goods_id = r.goods_id")->order("r.price");
                    break;
                case "sort_sales":
                    $db->order("sales_sum", "desc");
                    break;
                default:
                    break;
            }
        }
        $field = "k_goods.goods_id as goodsId,k_goods.last_update as lastUpdate,k_goods.is_on_sale as isOnSale,goods_name as goodsName,k_goods.goods_id as price,original_img as originalImg,sales_sum as salesSum,prom_id as address";
        // 只查询当前用户下的数据
        $data = $db->field($field)->where(['prom_id' => $admin['business']])->page($page, $listRows)->select();
        $this->rest($data);
    }

    /**
     * @title 商品详情
     * @desc  {"0":"接口地址：http://api.huaxiaoujia.com/index/goods/detailed","1":"请求方式：GET","2":"接口备注：必传参数用于加密验证"}
     * @param {"name":"goods_id","type":"int","required":true,"default":"","desc":"商品ID"}
     * @return {"name":"goodsId","type":"int","required":true,"desc":"商品ID","level":1}
     * @return {"name":"goodsName","type":"string","required":true,"desc":"商品名称","level":1}
     * @return {"name":"originalImg","type":"string","required":true,"desc":"商品封面图片","level":1}
     * @return {"name":"salesSum","type":"int","required":true,"desc":"商品销量","level":1}
     * @return {"name":"priceList","type":"array","required":true,"desc":"商品规格集合","level":1}
     * @return {"name":"content","type":"array","required":true,"desc":"商品介绍图片集合","level":1}
     * @return {"name":"collection","type":"boolean","required":true,"desc":"是否收藏","level":1}
     */

    public function detailed()
    {
        $user = $this->getUserInfo();
        if (input('goods_id')) {
            $userID = $user["user_id"];

            $data = model('Goods')->field("goods_id as goodsId,goods_name as goodsName,original_img as originalImg,sales_sum as salesSum,true as collection,goods_id as priceList,goods_content as content")->find(input('goods_id'));
            if ($data) {
                if ($userID > 0) {
                    //判断用户是否登陆
                    $collection = db('user_shop_goods')->where(["goods_id" => input('goods_id'), "user_id" => $userID, "status" => 1])->find();
                    if ($collection) {
                        $data["collection"] = true;
                    } else {
                        $data["collection"] = false;
                    }
                } else {
                    $data["collection"] = false;
                }
                $this->rest($data);
            } else {
                $this->rest('商品不存在', 's004');
            }
        } else {
            $this->rest('参数错误', 's004');
        }
    }

    /**
     * @title 商品规格
     * @desc  {"0":"接口地址：http://api.huaxiaoujia.com/index/goods/spec","1":"请求方式：GET","2":"接口备注：必传参数用于加密验证"}
     * @param {"name":"uid","type":"int","required":true,"default":"","desc":"用户ID"}
     * @param {"name":"time","type":"int","required":true,"default":"","desc":"当前时间"}
     * @param {"name":"token","type":"int","required":true,"default":"","desc":"用户操作token"}
     * @param {"name":"goods_id","type":"int","required":true,"default":"","desc":"商品ID"}
     * @return {"name":"id","type":"int","required":true,"desc":"规格ID","level":1}
     * @return {"name":"goods_id","type":"int","required":true,"desc":"商品ID","level":1}
     * @return {"name":"name","type":"string","required":true,"desc":"规格名称","level":1}
     * @return {"name":"price","type":"float","required":true,"desc":"销售价格","level":1}
     * @return {"name":"company","type":"string","required":true,"desc":"计价单位","level":1}
     * @return {"name":"count","type":"int","required":true,"desc":"库存","level":1}
     * @return {"name":"img","type":"strint","required":true,"desc":"规格图片","level":1}
     */

    public function spec()
    {
        if (input('goods_id')) {
            $data = db('spec_goods_price')->where('goods_id', input('goods_id'))->select();
            if ($data) {
                $this->rest($data);
            } else {
                $this->rest('规格不存在', 's004');
            }
        } else {
            $this->rest('参数错误', 's004');
        }
    }

    /**
     * @title 获取相册
     * @desc  {"0":"接口地址：http://api.huaxiaoujia.com/index/goods/images","1":"请求方式：GET","2":"接口备注：必传参数用于加密验证"}
     * @param {"name":"uid","type":"int","required":true,"default":"","desc":"用户ID"}
     * @param {"name":"time","type":"int","required":true,"default":"","desc":"当前时间"}
     * @param {"name":"token","type":"int","required":true,"default":"","desc":"用户操作token"}
     * @param {"name":"goods_id","type":"int","required":true,"default":"","desc":"商品ID"}
     * @return {"name":"id","type":"int","required":true,"desc":"规格ID","level":1}
     * @return {"name":"goods_id","type":"int","required":true,"desc":"商品ID","level":1}
     * @return {"name":"img","type":"string","required":true,"desc":"图片路径","level":1}
     */

    public function images()
    {
        if (input('goods_id')) {
            $data = model('goodsImages')->field("image_url as imageUrl")->where('goods_id', input('goods_id'))->select();
            if ($data) {
                $this->rest($data);
            } else {
                $this->rest('图片不存在', 's004');
            }
        } else {
            $this->rest('参数错误', 's004');
        }
    }

    /**
     * @title 收藏商品
     * @desc  {"0":"接口地址：http://api.huaxiaoujia.com/index/goods/collection","1":"请求方式：GET","2":"接口备注：必传参数用于加密验证"}
     * @param {"name":"uid","type":"int","required":true,"default":"","desc":"用户ID"}
     * @param {"name":"time","type":"int","required":true,"default":"","desc":"当前时间"}
     * @param {"name":"token","type":"int","required":true,"default":"","desc":"用户操作token"}
     * @param {"name":"goods_id","type":"int","required":true,"default":"","desc":"商品ID"}
     * @param {"name":"action","type":"int","required":true,"default":"","desc":"操作方式[insert,delete],不传默认查询方法，只有查询方法有返回参数"}
     * @return {"name":"id","type":"int","required":true,"desc":"规格ID","level":1}
     * @return {"name":"user_id","type":"int","required":true,"desc":"用户ID","level":1}
     * @return {"name":"goods_id","type":"int","required":true,"desc":"商品ID","level":1}
     * @return {"name":"status","type":"int","required":true,"desc":"状态","level":1}
     * @return {"name":"add_time","type":"int","required":true,"desc":"添加时间","level":1}
     */

    public function collection()
    {
        $userId = $this->isCheckAuth();
        $action = input('action');
        $db = db('user_shop_goods');
        switch ($action) {
            case 'insert':
                if (input('goods_id') && $userId) {
                    #判断商品是否存在
                    if (!db('goods')->where('goods_id', input('goods_id'))->find()) {
                        $this->rest('商品不存在', 's004');
                    }
                    #判断是否收藏过改商品
                    $res = $db->where(['user_id' => $userId, 'goods_id' => input('goods_id')])->find();
                    if ($res) {
                        //由于删除收藏是逻辑删除，判断之前是否有删除过该条收藏
                        if ($res['status'] == 1) {
                            $this->rest('已经收藏过该商品');
                        } else {
                            $res = $db->where(['user_id' => $userId, 'goods_id' => input('goods_id')])->setField('status', 1);
                            if ($res) {
                                $this->rest('收藏成功');
                            } else {
                                $this->rest('收藏失败', 's005');
                            }
                        }
                    }
                    //id, user_id, goods_id, sales, status, time
                    $data = array(
                        'goods_id' => input('goods_id'),
                        'user_id' => $userId,
                        'status' => 1,
                        'time' => time(),
                    );
                    if ($db->insert($data)) {
                        $this->rest('收藏成功');
                    } else {
                        $this->rest('收藏失败', 's005');
                    }
                } else {
                    $this->rest('参数错误', 's004');
                }
                break;
            case 'delete':
                if (input('goods_id') && $userId > 0) {
                    $res = $db->where(['user_id' => $userId, 'goods_id' => input('goods_id')])->setField('status', 0);
                    if ($res === false) {
                        $this->rest('移除错误', 's005');
                    } else {
                        $this->rest('成功移除');
                    }
                } else {
                    $this->rest('参数错误', 's004');
                }
                break;
            default:
                #默认查询收藏列表
                $data = $this->getCollection($userId);
                $this->rest($data);
                break;
        }
    }

    /**
     * @title 获取商品分类
     * @desc  {"0":"接口地址：http://api.huaxiaoujia.com/index/goods/getCategory","1":"请求方式：GET","2":"接口备注：必传参数用于加密验证"}
     */
    public function getCategory()
    {
        //k_goods_category
        $data = model("Category")->field("id,name,is_hot as isHot,id as item")->where(["pid" => 0, "is_show" => 1])->order("sort_order")->select();
        $this->rest($data);
    }

    public function getProm()
    {
        $page = input('page') > 0 ? input('page') : 1;
        $listRows = input('listRows') > 0 ? input('listRows') : 20;
        $db = model('Goods');
        $field = "g.goods_id as goodsId,goods_name as goodsName,g.goods_id as price,p.market_price as marketPrice,original_img as originalImg,sales_sum as salesSum,group_num groupNum,group_num_now as groupNumNow,prom_id as address,p.end_time as emdTime";
        $data = $db->alias("g")->field($field)->page($page, $listRows)->join("k_prom p", "g.goods_id = p.goods_id")->where("end_time > now()")->select();
        $this->rest($data);
    }

    /**
     * 获取收藏列表
     * @param $userId
     * @return mixed
     */
    private function getCollection($userId)
    {
        $page = input('page') > 0 ? input('page') : 1;
        $listRows = input('listRows') > 0 ? input('listRows') : 20;
        $db = model('Goods');
        $field = "g.goods_id as goodsId,goods_name as goodsName,g.goods_id as price,original_img as originalImg,sales_sum as salesSum,prom_id as address";
        $data = $db->alias("g")->field($field)->page($page, $listRows)->join("k_user_shop_goods c", "c.goods_id = g.goods_id")->where('c.user_id', $userId)->select();
        return $data;
    }
}
